[[...path]].page.tsx 9.8 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267
  1. import React, { useEffect } from 'react';
  2. import { type IUserHasId, type IPagePopulatedToShowRevision, getIdForRef } from '@growi/core';
  3. import type {
  4. GetServerSideProps, GetServerSidePropsContext,
  5. } from 'next';
  6. import { serverSideTranslations } from 'next-i18next/serverSideTranslations';
  7. import Head from 'next/head';
  8. import superjson from 'superjson';
  9. import { useLayoutFluidClassNameByPage } from '~/client/services/layout';
  10. import { ShareLinkLayout } from '~/components/Layout/ShareLinkLayout';
  11. import GrowiContextualSubNavigationSubstance from '~/components/Navbar/GrowiContextualSubNavigation';
  12. import { DrawioViewerScript } from '~/components/Script/DrawioViewerScript';
  13. import { ShareLinkPageView } from '~/components/ShareLinkPageView';
  14. import { SupportedAction, SupportedActionType } from '~/interfaces/activity';
  15. import type { CrowiRequest } from '~/interfaces/crowi-request';
  16. import type { RendererConfig } from '~/interfaces/services/renderer';
  17. import type { IShareLinkHasId } from '~/interfaces/share-link';
  18. import type { PageDocument } from '~/server/models/page';
  19. import ShareLink from '~/server/models/share-link';
  20. import {
  21. useCurrentUser, useRendererConfig, useIsSearchPage, useCurrentPathname,
  22. useShareLinkId, useIsSearchServiceConfigured, useIsSearchServiceReachable, useIsSearchScopeChildrenAsDefault, useIsContainerFluid, useIsEnabledMarp,
  23. } from '~/stores/context';
  24. import { useCurrentPageId, useIsNotFound, useSWRMUTxCurrentPage } from '~/stores/page';
  25. import loggerFactory from '~/utils/logger';
  26. import type { NextPageWithLayout } from '../_app.page';
  27. import {
  28. getServerSideCommonProps, generateCustomTitleForPage, getNextI18NextConfig, CommonProps, skipSSR,
  29. } from '../utils/commons';
  30. const logger = loggerFactory('growi:next-page:share');
  31. type Props = CommonProps & {
  32. shareLinkRelatedPage?: IShareLinkRelatedPage,
  33. shareLink?: IShareLinkHasId,
  34. isNotFound: boolean,
  35. isExpired: boolean,
  36. disableLinkSharing: boolean,
  37. isSearchServiceConfigured: boolean,
  38. isSearchServiceReachable: boolean,
  39. isSearchScopeChildrenAsDefault: boolean,
  40. isEnabledMarp: boolean,
  41. drawioUri: string | null,
  42. rendererConfig: RendererConfig,
  43. skipSSR: boolean,
  44. ssrMaxRevisionBodyLength: number,
  45. };
  46. type IShareLinkRelatedPage = IPagePopulatedToShowRevision & PageDocument;
  47. superjson.registerCustom<IShareLinkRelatedPage, string>(
  48. {
  49. isApplicable: (v): v is IShareLinkRelatedPage => {
  50. return v != null
  51. && v.toObject != null
  52. && v.lastUpdateUser != null
  53. && v.creator != null
  54. && v.revision != null;
  55. },
  56. serialize: (v) => { return superjson.stringify(v.toObject()) },
  57. deserialize: (v) => { return superjson.parse(v) },
  58. },
  59. 'IShareLinkRelatedPageTransformer',
  60. );
  61. // GrowiContextualSubNavigation for shared page
  62. // get page info from props not to send request 'GET /page' from client
  63. type GrowiContextualSubNavigationForSharedPageProps = {
  64. page?: IPagePopulatedToShowRevision,
  65. isLinkSharingDisabled: boolean,
  66. }
  67. const GrowiContextualSubNavigationForSharedPage = (props: GrowiContextualSubNavigationForSharedPageProps): JSX.Element => {
  68. const { page, isLinkSharingDisabled } = props;
  69. return (
  70. <GrowiContextualSubNavigationSubstance currentPage={page} isLinkSharingDisabled={isLinkSharingDisabled} />
  71. );
  72. };
  73. const SharedPage: NextPageWithLayout<Props> = (props: Props) => {
  74. useCurrentPathname(props.shareLink?.relatedPage.path);
  75. useIsSearchPage(false);
  76. useIsNotFound(props.isNotFound);
  77. useShareLinkId(props.shareLink?._id);
  78. useCurrentPageId(props.shareLink?.relatedPage._id);
  79. useCurrentUser(props.currentUser);
  80. useRendererConfig(props.rendererConfig);
  81. useIsSearchServiceConfigured(props.isSearchServiceConfigured);
  82. useIsSearchServiceReachable(props.isSearchServiceReachable);
  83. useIsSearchScopeChildrenAsDefault(props.isSearchScopeChildrenAsDefault);
  84. useIsEnabledMarp(props.rendererConfig.isEnabledMarp);
  85. useIsContainerFluid(props.isContainerFluid);
  86. const { trigger: mutateCurrentPage, data: currentPage } = useSWRMUTxCurrentPage();
  87. useEffect(() => {
  88. if (!props.skipSSR) {
  89. return;
  90. }
  91. if (props.shareLink?.relatedPage._id != null && !props.isNotFound) {
  92. mutateCurrentPage();
  93. }
  94. }, [mutateCurrentPage, props.isNotFound, props.shareLink?.relatedPage._id, props.skipSSR]);
  95. const growiLayoutFluidClass = useLayoutFluidClassNameByPage(props.shareLinkRelatedPage);
  96. const pagePath = props.shareLinkRelatedPage?.path ?? '';
  97. const title = generateCustomTitleForPage(props, pagePath);
  98. return (
  99. <>
  100. <Head>
  101. <title>{title}</title>
  102. </Head>
  103. <div className={`dynamic-layout-root ${growiLayoutFluidClass} justify-content-between`}>
  104. <nav className="sticky-top">
  105. <GrowiContextualSubNavigationForSharedPage page={currentPage ?? props.shareLinkRelatedPage} isLinkSharingDisabled={props.disableLinkSharing} />
  106. </nav>
  107. <div id="grw-fav-sticky-trigger" className="sticky-top"></div>
  108. <ShareLinkPageView
  109. pagePath={pagePath}
  110. rendererConfig={props.rendererConfig}
  111. page={currentPage ?? props.shareLinkRelatedPage}
  112. shareLink={props.shareLink}
  113. isExpired={props.isExpired}
  114. disableLinkSharing={props.disableLinkSharing}
  115. />
  116. </div>
  117. </>
  118. );
  119. };
  120. SharedPage.getLayout = function getLayout(page) {
  121. return (
  122. <>
  123. <DrawioViewerScript />
  124. <ShareLinkLayout>{page}</ShareLinkLayout>
  125. </>
  126. );
  127. };
  128. function injectServerConfigurations(context: GetServerSidePropsContext, props: Props): void {
  129. const req: CrowiRequest = context.req as CrowiRequest;
  130. const { crowi } = req;
  131. const { configManager, searchService } = crowi;
  132. props.disableLinkSharing = configManager.getConfig('crowi', 'security:disableLinkSharing');
  133. props.isSearchServiceConfigured = searchService.isConfigured;
  134. props.isSearchServiceReachable = searchService.isReachable;
  135. props.isSearchScopeChildrenAsDefault = configManager.getConfig('crowi', 'customize:isSearchScopeChildrenAsDefault');
  136. props.drawioUri = configManager.getConfig('crowi', 'app:drawioUri');
  137. props.rendererConfig = {
  138. isSharedPage: true,
  139. isEnabledLinebreaks: configManager.getConfig('markdown', 'markdown:isEnabledLinebreaks'),
  140. isEnabledLinebreaksInComments: configManager.getConfig('markdown', 'markdown:isEnabledLinebreaksInComments'),
  141. isEnabledMarp: configManager.getConfig('crowi', 'customize:isEnabledMarp'),
  142. adminPreferredIndentSize: configManager.getConfig('markdown', 'markdown:adminPreferredIndentSize'),
  143. isIndentSizeForced: configManager.getConfig('markdown', 'markdown:isIndentSizeForced'),
  144. drawioUri: configManager.getConfig('crowi', 'app:drawioUri'),
  145. plantumlUri: configManager.getConfig('crowi', 'app:plantumlUri'),
  146. // XSS Options
  147. isEnabledXssPrevention: configManager.getConfig('markdown', 'markdown:rehypeSanitize:isEnabledPrevention'),
  148. xssOption: configManager.getConfig('markdown', 'markdown:rehypeSanitize:option'),
  149. attrWhitelist: JSON.parse(crowi.configManager.getConfig('markdown', 'markdown:rehypeSanitize:attributes')),
  150. tagWhitelist: crowi.configManager.getConfig('markdown', 'markdown:rehypeSanitize:tagNames'),
  151. highlightJsStyleBorder: configManager.getConfig('crowi', 'customize:highlightJsStyleBorder'),
  152. };
  153. props.ssrMaxRevisionBodyLength = configManager.getConfig('crowi', 'app:ssrMaxRevisionBodyLength');
  154. }
  155. async function injectNextI18NextConfigurations(context: GetServerSidePropsContext, props: Props, namespacesRequired?: string[] | undefined): Promise<void> {
  156. const nextI18NextConfig = await getNextI18NextConfig(serverSideTranslations, context, namespacesRequired);
  157. props._nextI18Next = nextI18NextConfig._nextI18Next;
  158. }
  159. function getAction(props: Props): SupportedActionType {
  160. let action: SupportedActionType;
  161. if (props.isExpired) {
  162. action = SupportedAction.ACTION_SHARE_LINK_EXPIRED_PAGE_VIEW;
  163. }
  164. else if (props.shareLink == null) {
  165. action = SupportedAction.ACTION_SHARE_LINK_NOT_FOUND;
  166. }
  167. else {
  168. action = SupportedAction.ACTION_SHARE_LINK_PAGE_VIEW;
  169. }
  170. return action;
  171. }
  172. async function addActivity(context: GetServerSidePropsContext, action: SupportedActionType): Promise<void> {
  173. const req: CrowiRequest = context.req as CrowiRequest;
  174. const parameters = {
  175. ip: req.ip,
  176. endpoint: req.originalUrl,
  177. action,
  178. user: req.user?._id,
  179. snapshot: {
  180. username: req.user?.username,
  181. },
  182. };
  183. await req.crowi.activityService.createActivity(parameters);
  184. }
  185. export const getServerSideProps: GetServerSideProps = async(context: GetServerSidePropsContext) => {
  186. const req = context.req as CrowiRequest;
  187. const { crowi, params } = req;
  188. const result = await getServerSideCommonProps(context);
  189. if (!('props' in result)) {
  190. throw new Error('invalid getSSP result');
  191. }
  192. const props: Props = result.props as Props;
  193. try {
  194. const shareLink = await ShareLink.findOne({ _id: params.linkId }).populate('relatedPage');
  195. if (shareLink == null) {
  196. props.isNotFound = true;
  197. }
  198. else {
  199. props.isNotFound = false;
  200. props.isExpired = shareLink.isExpired();
  201. props.shareLink = shareLink.toObject();
  202. // retrieve Page
  203. const Page = crowi.model('Page');
  204. const relatedPage = await Page.findOne({ _id: getIdForRef(shareLink.relatedPage) });
  205. // determine whether skip SSR
  206. const ssrMaxRevisionBodyLength = crowi.configManager.getConfig('crowi', 'app:ssrMaxRevisionBodyLength');
  207. props.skipSSR = await skipSSR(relatedPage, ssrMaxRevisionBodyLength);
  208. // populate
  209. props.shareLinkRelatedPage = await relatedPage.populateDataToShowRevision(props.skipSSR); // shouldExcludeBody = skipSSR
  210. }
  211. }
  212. catch (err) {
  213. logger.error(err);
  214. }
  215. injectServerConfigurations(context, props);
  216. await injectNextI18NextConfigurations(context, props);
  217. await addActivity(context, getAction(props));
  218. return {
  219. props,
  220. };
  221. };
  222. export default SharedPage;